package scrum.client.project;

import ilarkesto.gwt.client.ButtonWidget;

import java.util.ArrayList;
import java.util.List;

import scrum.client.common.AScrumWidget;
import scrum.client.common.BlockListWidget;
import scrum.client.workspace.PagePanel;

import com.google.gwt.user.client.ui.Widget;

public class ProjectGroupWidget extends AScrumWidget {

	public BlockListWidget<ProjectGroup> list;

	@Override
	protected Widget onInitialization() {

		list = new BlockListWidget<ProjectGroup>(ProjectGroupBlock.FACTORY);
		list.setAutoSorter(ProjectGroup.LABEL_COMPARATOR);

		PagePanel page = new PagePanel();

		page.addHeader("Groups", new ButtonWidget(new CreateProjectGroupAction()));
		page.addSection(list);

		return page;
	}

	@Override
	protected void onUpdate() {
		// Only shows the ProjectGroups for the currently open project => we need to filter the results!

		List<ProjectGroup> allGroups = getDao().getProjectGroups();
		Project currProject = getCurrentProject(); // need: an open project, otherwise assertion will fail

		List<ProjectGroup> filtered = new ArrayList<ProjectGroup>();
		for (ProjectGroup pg : allGroups) {
			if (pg.getProject().equals(currProject)) filtered.add(pg);
		}

		list.setObjects(filtered);

		super.onUpdate();
	}

	public boolean select(ProjectGroup group) {
		if (!list.contains(group)) update();
		return list.showObject(group);
	}

}
